﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace FolderSync
{
    class Program
    {
        private static string _mEorrStr;
        //private const string FromToFormat = @"FROM\[[a-zA-Z]\:[\\a-zA-Z0-9_\\]+[\.]?[a-zA-Z0-9_]+\]TO\[[a-zA-Z]\:[\\a-zA-Z0-9_\\]+[\.]?[a-zA-Z0-9_]+\]";
        private const string FromToFormat = @"FROM\[(?<from>.*?)]TO\[(?<to>.*?)\]";

        static void Main(string[] args)
        {
            ReadFromTo();
        }

        private static SyncInfo[] ReadFromTo()
        {
            var regex = new Regex(FromToFormat);
            var sr = new StreamReader("fromto.txt", Encoding.Default);
            var list = new List<SyncInfo>();
            string s;
            while ((s = sr.ReadLine()) != null)
            {
                if (regex.IsMatch(s))
                {
                    var match = regex.Match(s);
                    var si = new SyncInfo(match.Groups["from"].Value, match.Groups["to"].Value);
                    list.Add(si);
                }
            }
            return list.ToArray();
        }

        private static void CopyFiles(string fromDirectory, string toDirectory)
        {
            //实现从一个目录下完整拷贝到另一个目录下。
            Directory.CreateDirectory(toDirectory);
            if (!Directory.Exists(fromDirectory))
            {
                _mEorrStr = "对不起，您要拷贝的目录不存在。 ";
                return;
            }

            var directories = Directory.GetDirectories(fromDirectory);//取文件夹下所有文件夹名，放入数组；
            if (directories.Length > 0)
            {
                foreach (var d in directories)
                {
                    CopyFiles(d, toDirectory + d.Substring(d.LastIndexOf("\\")));//递归拷贝文件和文件夹
                }
            }

            var files = Directory.GetFiles(fromDirectory);//取文件夹下所有文件名，放入数组；
            if (files.Length > 0)
            {
                foreach (var s in files)
                {
                    File.Copy(s, toDirectory + s.Substring(s.LastIndexOf("\\")));
                }
            }
        }
    }

    public class SyncInfo
    {
        public SyncInfo(string from, string to)
        {
            if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to))
            {
                throw new Exception("路径不正确");
            }
            FromDirectory = from;
            ToDirectory = to;
        }

        public string FromDirectory { get; set; }

        public string ToDirectory { get; set; }

        public string[] IgnoreRules { get; set; }
    }
}
